package com.qys.training.biz.auth.service.impl;

import com.qys.training.base.enumerate.BizCodeEnum;
import com.qys.training.base.exception.QysException;
import com.qys.training.biz.utils.CypherUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qys.training.biz.auth.entity.User;
import com.qys.training.biz.auth.mapper.UserMapper;
import com.qys.training.biz.auth.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 创建用户，将密码加密，用户名不能重复
     *
     * @param user
     * @return id
     */
    public Long create(User user) {
        User oldUser = userMapper.selectByUsername(user.getUsername());
        if (oldUser != null){
            throw new QysException(BizCodeEnum.USERNAME_ALREADY_EXISTS.getCode(),BizCodeEnum.USERNAME_ALREADY_EXISTS.getDescription());
        }else {
            user.setPassword(CypherUtil.encoderByMd5(user.getPassword()));
            userMapper.insert(user);
        }
        return user.getId();
    }

    /**
     * 验证⽤用户名和密码是否正确
     * @param user
     * @return
     */
    public Boolean checkUser (User user) {
        User registeredUser = userMapper.selectByUsername(user.getUsername());
        if (registeredUser == null){
            throw new QysException(BizCodeEnum.USER_DOES_NOT_EXIST.getCode(),BizCodeEnum.USER_DOES_NOT_EXIST.getDescription());
        }else {
            return CypherUtil.verifyEncryption(user.getPassword(),registeredUser.getPassword());
        }
    }

    public void testQysException() {
        throw new QysException(BizCodeEnum.ERROR.getCode(), BizCodeEnum.ERROR.getDescription());
    }

    public void testOtherException() {
        int error = 10 / 0;
    }
}
